package com.springcloud.tools.conf;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisNode;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;

import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

/**
 * @author fuc
 * @create 2020-06-07
 */
@Configuration
public class RedisConfig {

  @Value("${spring.redis.cluster.nodes}")
  private String clusterNodes;

  @Value("${spring.redis.password}")
  private String redisPassWord;

  @Value("${redis.auth}")
  private String auth;

  @Bean
  public RedisClusterConfiguration getRedisCluster() {
    Set<RedisNode> lettuceClusterNodes = new HashSet<RedisNode>();
    String[] nodes = clusterNodes.split(",");
    for (String node : nodes) {
      String[] table = node.split(":");
      lettuceClusterNodes.add(new RedisNode(table[0], Integer.parseInt(table[1])));
    }
    RedisClusterConfiguration redisClusterConfiguration = new RedisClusterConfiguration();
    redisClusterConfiguration.setClusterNodes(lettuceClusterNodes);
    return redisClusterConfiguration;
  }

  @Bean
  public LettuceConnectionFactory lettuceConnectionFactory() {
    LettuceConnectionFactory redisConnectionFactory =
        new LettuceConnectionFactory(getRedisCluster());
    if (Objects.equals(auth, "1")) {
      redisConnectionFactory.setPassword(redisPassWord);
    }
    return redisConnectionFactory;
  }

  @Bean
  public RedisConnection getConnectionFactory(LettuceConnectionFactory lettuceConnectionFactory) {
    RedisConnection connection = lettuceConnectionFactory.getConnection();
    return connection;
  }

  @Bean
  public RedisTemplate<Object, Object> redisTemplate(
      LettuceConnectionFactory lettuceConnectionFactory) {
    RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
    redisTemplate.setConnectionFactory(lettuceConnectionFactory);
    // 使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值（默认使用JDK的序列化方式）
    Jackson2JsonRedisSerializer jackson2JsonRedisSerializer =
        new Jackson2JsonRedisSerializer(Object.class);
    redisTemplate.setDefaultSerializer(jackson2JsonRedisSerializer);

    return redisTemplate;
  }
}
